<?php
/***********************************************************
 * 模型管理
 * @作者 pcfcms <1131680521@qq.com>
 * @主页 http://www.pcfcms.com
 * @时间 2021年01月01日
***********************************************************/
namespace app\admin\model;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Request;
use app\admin\model\FieldType;
class ChannelType extends Common
{
    //列表
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = 10;
        }
        $list = Db::name('channel_type')->order('sort_order asc')->paginate($limit)->toArray();
        $pcfdata = $list['data'];
        $newdata = [];
        foreach ($pcfdata as $key => $value) {
            $newdata[$key]['id'] = $value['id'];
            $newdata[$key]['nid'] = $value['nid'];
            $newdata[$key]['title'] = $value['title'];
            $newdata[$key]['icon'] = $value['icon'];
            $newdata[$key]['ifsystem'] = $value['ifsystem'];
            $newdata[$key]['sort_order'] = $value['sort_order'];
            $newdata[$key]['status'] = $value['status'];
        }
        $result = ['code' => 0, 'msg' => 'ok','count' =>$list['total'],'data' => $newdata];
        return $result;
    }

    //添加|编辑
    public function toAdd($data, $channeltype_system_nid)
    {
        $domain = Request::baseFile().'/type/index';
        //判断是新增还是修改
        if (isset($data['id']) && !empty($data['id'])) {
            $where = [];
            $where[] = ['nid','=',$data['nid']];
            $where[] = ['id','<>',$data['id']];
            $edit_data = [];
            if (empty($data['ntitle'])) {
                $result = ['status' => false,'msg' => '模型名称不能为空！'];
                return $result;
            }
            if(Db::name('channel_type')->where($where)->count('id') > 0){
                $result = ['status' => false,'msg' => '该模型标识已存在，请检查','url' => $domain];
                return $result;
            }
            $edit_data['nid'] = $data['nid'];
            $edit_data['title']  = $data['ntitle']."模型";
            $edit_data['ntitle']  = $data['ntitle'];
            $edit_data['table'] = $data['nid'];
            $edit_data['icon'] = $data['icon'];
            $edit_data['ctl_name'] = ucfirst($data['nid']);
            $edit_data['is_repeat_title'] = $data['is_repeat_title'];
            $edit_data['add_time'] = getTime();
            if (Db::name('channel_type')->where('id', $data['id'])->data($edit_data)->update()) {
                $result = ['status' => true,'msg' => '修改成功','url' => $domain];
                return $result;
            } else {
                $result = ['status' => false,'msg' => '修改失败'];
                return $result;
            }
        } else {
            //判断用户名是否重复
            $manageInfo = Db::name('channel_type')->where('ntitle', $data['ntitle'])->find();
            $data['ntitle'] = trim($data['ntitle']);
            if (!$data['ntitle']) {
                $result = ['status' => false,'msg' => '模型名称不能为空！'];
                return $result;
            }
            if (!$data['nid']) {
                $result = ['status' => false,'msg' => '输入模型标识'];
                return $result;
            }else{
                if(Db::name('channel_type')->where('nid','=',$data['nid'])->count('id') > 0){
                    $result = ['status' => false,'msg' => '该模型标识已存在，请检查'];
                    return $result;
                }
                if (!preg_match('/^([a-z]+)([a-z0-9]*)$/i', $data['nid'])) {
                    $result = ['status' => false,'msg' => '模型标识必须以小写字母开头！'];
                    return $result;
                } else if (in_array($data['nid'], $channeltype_system_nid)) {
                    $result = ['status' => false,'msg' => '系统禁用当前模型标识，请更改！'];
                    return $result;
                }
            }
            $post['ntitle'] = $data['ntitle'];
            $post['is_repeat_title'] = $data['is_repeat_title'];
            $post['nid'] = strtolower($data['nid']);
            $nid = $post['nid'];
            $post['ctl_name'] = ucwords($nid);
            $post['table']    = $nid;
            if ($manageInfo) {
                $result = ['status' => false,'msg' => '模型已存在'];
                return $result;
            }
            $this->create_sql_file($post); // 创建文件以及数据表
            $add_data = [
                'title'        => $data['ntitle'].'模型',
                'ntitle'        => $data['ntitle'],
                'nid'           => $nid,
                'icon'          => $data['icon'],
                'add_time'      => getTime(),
                'update_time'   => getTime()
            ];
            $add_data = array_merge($post, $add_data);         
            $insertId = Db::name('channel_type')->insertGetId($add_data);
            if ($insertId) {
                //复制模型字段基础数据
                $FieldType = new FieldType;
                $FieldType->ArchivesTable($insertId,"");
                try {
                    schemaTable($data['table'].'_content'); //生成数据表字段信息缓存
                } catch (\Exception $e) {}
                Cache::clear();
                $result = ['status' => true,'msg' => '添加成功','url'=>$domain];
                return $result;
            } else {
                $result = ['status' => false,'msg' => '添加失败'];
                return $result;
            }
        }
    }


    // 创建文件以及数据表
    private function create_sql_file($post) 
    {
        $demopath = WWW_ROOT.'extend/pcfcms/';
        $fileArr = []; // 生成的相关文件记录
        $filelist = [
            "app/home/controller/CustomModel.php",
            "app/home/model/CustomModel.php",
            "template/default/pc/lists_custommodel.html",
            "template/default/pc/view_custommodel.html"
        ];
        foreach ($filelist as $key => $file) {
            $dst1 = $file;
            $dst1 = str_replace('CustomModel', $post['ctl_name'], $dst1);
            $dst1 = str_replace('custommodel', $post['nid'], $dst1);
            //记录相关文件
            if (!stristr($dst1, 'custom_path')) {
                array_push($fileArr, $dst1);
            }
            $src = $demopath.$file;

            if(0 == $key || 1 == $key){
                $dst = WWW_ROOT.$file;
            }elseif(2 == $key || 3 == $key){
                $dst = WWW_ROOT.'public/'.$file;
            }

            $dst = str_replace('CustomModel', $post['ctl_name'], $dst);
            $dst = str_replace('custommodel', $post['nid'], $dst);
            if(tp_mkdir(dirname($dst))) {
                $fileContent = @file_get_contents($src);
                $fileContent = str_replace('CustomModel', $post['ctl_name'], $fileContent);
                $fileContent = str_replace('custommodel', strtolower($post['nid']), $fileContent);
                $fileContent = str_replace('CUSTOMMODEL', strtoupper($post['nid']), $fileContent);
                $view_suffix = config('view.view_suffix');
                if (stristr($file, 'lists_custommodel.'.$view_suffix)) {
                    $replace = <<<EOF
<section class="article-list">
                    {gzpcf:list pagesize="10" titlelen="38"}
                    <article>
                        {gzpcf:notempty name="\$field.is_litpic"}
                        <a href="{\$field.arcurl}" title="{\$field.title}" style="float:left;margin-right:10px"> <img src="{\$field.litpic}" alt="{\$field.title}" height="100" /> </a>
                        {/gzpcf:notempty} 
                        <h2><a href="{\$field.arcurl}" class="">{\$field.title}</a><span>{\$field.click}°C</span></h2>
                        <div class="excerpt">
                            <p>{\$field.seo_description}</p>
                        </div>
                        <div class="meta">
                            <span class="item"><time>{\$field.add_time|MyDate='Y-m-d',###}</time></span>
                            <span class="item">{\$field.typename}</span>
                        </div>
                    </article>
                    {/gzpcf:list}
                </section>
                <section class="list-pager">
                    {gzpcf:pagelist listitem='index,pre,pageno,next,end' listsize='2'/}
                    <div class="clear"></div>
                </section>
EOF;
                    $fileContent = str_replace("<!-- #list# -->", $replace, $fileContent);
                }
                $puts = file_put_contents($dst, $fileContent);
                if (!$puts) {
                    $result = ['status' => false,'msg' => '创建自定义模型生成相关文件失败，请检查站点目录权限！'];
                    return $result;
                }
            }
        }
        @file_put_contents($demopath.'custom_path/'.$post['nid'].'.filelist.txt', implode("\n\r", $fileArr));
        $table = config('database.connections.mysql.prefix').$post['table'].'_content';
        $tableSql = <<<EOF
CREATE TABLE `{$table}` (
  `id`          int(10) NOT NULL    AUTO_INCREMENT,
  `typeid`      int(10) DEFAULT '0' COMMENT         '栏目ID',
  `aid`         int(10) DEFAULT '0' COMMENT         '文档ID',
  `add_time`    int(11) DEFAULT '0' COMMENT         '新增时间',
  `update_time` int(11) DEFAULT '0' COMMENT         '更新时间',
  PRIMARY KEY (`id`),
  KEY `aid` (`aid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='附加表';
EOF;
        $sqlFormat  = $this->sql_split($tableSql, config('database.connections.mysql.prefix'));
        //执行SQL语句
        try {
            $counts = count($sqlFormat);
            for ($i = 0; $i < $counts; $i++) {
                $sql = trim($sqlFormat[$i]);
                if (stristr($sql, 'CREATE TABLE')) {
                    Db::execute($sql);
                } else {
                    if(trim($sql) == ''){continue;}
                    Db::execute($sql);
                }
            }
        } catch (\Exception $e) {
            $result = ['status' => false,'msg' => '创建文件以及数据表抛出异常！'];
            return $result;
        }
    }

    //解析sql语句
    private function sql_split($sql, $tablepre) 
    {  
        $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-'){
                    $ret[$num] .= $query;
                }
            }
            $num++;
        }
        return $ret;
    }

}
